<?php
namespace Macaca\Module\Admin;

use Macaca\Model;
use Monkey;

class Index {

    public /**
     * @var \Monkey\App
     */
        $app;

    private $modelAdminNav;
    private $modelPriKey;
    private $modelCacheKey = 'MacacaAdminNav';

    /**
     * @param Monkey\App $app
     */
    public function __construct($app) {
        $this->app = $app;
        $this->modelAdminNav = new Model\Admin\AdminNav($app);
        $this->modelPriKey = $this->modelAdminNav->priKey;
    }

    /**
     * @return array
     */
    public function getNav() {
        $result = array();
        $cache = $this->app->cache();
        if (!$cache->fetch($this->modelCacheKey, $result)) {
            $result = $this->getNavFromDatabase();
            $cache->store($this->modelCacheKey, $result);
        }
        return $result;
    }

    private function getNavFromDatabase() {
        $result = array();
        $nav = $this->modelAdminNav->findAll();
        $route = $this->app->router();
        $pk = $this->modelPriKey;

        foreach ($nav as $key => $item) {
            $nav[$key]['url'] = $route->toURL($nav[$key]['url']);

            if ($item[$pk] == $item['parent']) {
                $result[$item['sort']][-1] = $nav[$key];
                unset($nav[$key]);
            }
        }
        ksort($result);

        foreach ($result as $k => $group) {

            $parentId = $group[-1][$pk];

            foreach ($nav as $key => $item) {
                if ($parentId == $item['parent'] and $parentId != $item[$pk]) {
                    $group[] = $item;
                    unset($nav[$key]);
                }
            }

            if (count($group) > 1) {
                ksort($group);
                $result[$k] = $group;
            }

            if (empty($nav)) {
                break;
            }

        }

        return $result;
    }


    public function getShortcut() {
        //todo 生成快捷菜单项
        return array();
    }
} 